package com.dsc.image;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @author: Du Shun Chang
 * @title: ImageServlet
 * @date: 2022/2/5 20:20
 * @description: 图片验证码
 * @version：1.0
 */
public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*1.浏览器实现5秒自动刷新*/
        resp.setHeader("refresh", "5");
        /*2.在内存中创建图片类 图片大小以及颜色模式（RGB类型）*/
        BufferedImage bufferedImage = new BufferedImage(50, 20, BufferedImage.TYPE_INT_RGB);
        /*3.绘制图片*/
        Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
        /*4.设置背景颜色*/
        graphics2D.setColor(Color.white);
        graphics2D.fillRect(0, 0, 50, 20);
        /*5.将随机数填充图片*/
        graphics2D.setColor(Color.BLUE);
        graphics2D.setFont(new Font(null, Font.BOLD, 20));//设置字体的样式及大小
        graphics2D.drawString(randomnum(), 0, 20);//将随机数写入到图片中
        /*6.将图片已jpg的格式响应到浏览器中*/
        resp.setContentType("image/jpg");//设置响应的格式为图片ß
        /*7.设置浏览器不缓存*/
        resp.setDateHeader("expires", -1);
        resp.setHeader("Cache-control", "no-cache");
        resp.setHeader("Pragma", "no-cache");
        /*8.将图片响应到浏览器中*/
        ImageIO.write(bufferedImage, "jpg", resp.getOutputStream());
    }


    /**
     * @author:Du Shun Chang
     * @date:2022/2/6 14:18
     * @title:randomnum
     * @param:[]
     * @return: java.lang.String
     * @throws:
     * @description: 产生4为的随机数
     */
    private String randomnum() {
        Random random = new Random();
        String num = String.valueOf(random.nextInt(9999));//强制转化为string类型
        StringBuffer stringBuffer = new StringBuffer();
        /*不足四位时，用0填充*/
        for (int i = 0; i < 4 - num.length(); i++) {
            stringBuffer.append("0");
        }
        num = stringBuffer.toString() + num;
        System.out.println(num);
        return num;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
